package com.aleaho.cftrack.activity;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.aleaho.cftrack.CFTrackApplication;
import com.aleaho.cftrack.R;
import com.aleaho.cftrack.http.entity.SignEntity;
import com.aleaho.cftrack.presenter.SignPresenter;
import com.aleaho.cftrack.utils.CommonUtil;
import com.aleaho.cftrack.utils.Constants;
import com.aleaho.cftrack.utils.LocationUtil;
import com.aleaho.cftrack.utils.MapUtil;
import com.aleaho.cftrack.utils.ViewUtil;
import com.aleaho.cftrack.view.SignView;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;

import com.baidu.mapapi.model.LatLng;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;

public class SignActivity extends BaseActivity implements SignView {


    @BindView(R.id.mapView_sign)
    MapView mMapView;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.progress)
    ProgressWheel progressWheel;


    private CFTrackApplication trackApp = null;
    private boolean isGpsInit = false;
    private LatLng p1;
    private double distance = 10000;
    private String distanceString = "";
    private String address = "";
    private String addr = "";
    private boolean isFirstLocation = true;

    private SignPresenter signPresenter = null;


    private MapUtil mapUtil = null;
    private ViewUtil viewUtil = null;

    private String now = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }


    private void init() {
        setTitle(R.string.activity_sign);
        setBackView();
        trackApp = (CFTrackApplication) getApplicationContext();
        signPresenter = new SignPresenter(getApplicationContext(), this);
        mapUtil = new MapUtil();
        viewUtil = new ViewUtil();
        mapUtil.init(mMapView);
        mapUtil.initLocation(getApplicationContext(), new MyLocationListener());
    }


    public void onClick(View v) {
        isFirstLocation = true;
        mapUtil.requestLocation();
        ivLocation.setVisibility(View.GONE);
        progressWheel.setVisibility(View.VISIBLE);
    }


    public void onSignIn(View v) {

        Calendar cld = Calendar.getInstance();

        String now = CommonUtil.canlenderToTimeString(cld);
        String content = tvAddress.getText() + "\n\n" + tvDistance.getText() + "\n\n当前时间：" + now;

        confirmDialog(R.string.dialog_sign_in_title, content,
                R.string.dialog_sign_in_ok, R.string.dialog_sign_in_tip, cld, Constants.SIGN_IN);
    }


    public void onSignOut(View v) {

        Calendar cld = Calendar.getInstance();

        String now = CommonUtil.canlenderToTimeString(cld);

        String content = tvAddress.getText() + "\n\n" + tvDistance.getText() + "\n\n当前时间：" + now;

        confirmDialog(R.string.dialog_sign_out_title, content,
                R.string.dialog_sign_out_ok, R.string.dialog_sign_out_tip, cld, Constants.SIGN_OUT);
    }


    @Override
    public int getResourcesId() {
        return R.layout.activity_sign;
    }

    /**
     * 使用 {@link Toast}显示签到签退结果。
     * @param msg 签到签退结果。
     */
    @Override
    public void showMessage(String msg) {

        viewUtil.showToast(this, msg);
    }


    private void setTextView() {
        tvAddress.post(new Runnable() {
            @Override
            public void run() {
                ivLocation.setVisibility(View.VISIBLE);
                progressWheel.setVisibility(View.GONE);

                tvAddress.setText(address);
            }
        });

        tvDistance.post(new Runnable() {
            @Override
            public void run() {
                tvDistance.setText(distanceString);
            }
        });
    }


    private void confirmDialog(int titleRes, String content,
                               int posRes, final int resTip,
                               final Calendar cld, final int signType) {

        final int year = cld.get(Calendar.YEAR);
        final int month = cld.get(Calendar.MONTH) + 1;
        final int day = cld.get(Calendar.DAY_OF_MONTH);
        final int hour = cld.get(Calendar.HOUR_OF_DAY);
        final int minute = cld.get(Calendar.MINUTE);


        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(titleRes)
                .titleColor(Color.parseColor("#2196F3"))
                .content(content)
                .positiveText(posRes)
                .onPositive(new MaterialDialog.SingleButtonCallback() {

                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        //签到、签退

                        SignEntity se = new SignEntity();

                        se.setSigner(trackApp.getLoginEntity().getId());
                        se.setSign_type(signType);
                        se.setYear(year);
                        se.setMonth(month);
                        se.setDay(day);
                        se.setHour(hour);
                        se.setMinute(minute);
                        se.setDistance((int) distance);
                        se.setAddress(addr);
                        se.setLat(String.valueOf(p1.latitude));
                        se.setLng(String.valueOf(p1.longitude));

                        signPresenter.signInOrOut(se);
                    }
                })

                .negativeText(R.string.dialog_sign_cancel)
                .onNegative(new MaterialDialog.SingleButtonCallback() {

                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        Toast.makeText(SignActivity.this, resTip, Toast.LENGTH_LONG).show();

                    }
                })
                .show();
    }


    @Override
    protected void onStart() {
        super.onStart();
        checkGPS();

        isFirstLocation = true;
        ivLocation.setVisibility(View.GONE);
        progressWheel.setVisibility(View.VISIBLE);
    }


    private void checkGPS() {

        isGpsInit = LocationUtil.isLocationOpen((Context) trackApp);

        if (!isGpsInit) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage(R.string.open_gps_tip);
            dialog.setPositiveButton("确定",
                    new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, Constants.INIT_GPS_CODE);
                        }
                    });
            dialog.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                    Toast.makeText(SignActivity.this, R.string.open_gps_failed,
                            Toast.LENGTH_SHORT).show();
                }
            });
            dialog.show();
        } else {

            startLocation();
        }

    }

    private void startLocation() {

        mapUtil.startLocation();

    }


    @Override
    protected void onPause() {
        super.onPause();
        mapUtil.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapUtil.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapUtil.destroy();
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mapUtil.mapView == null) {
                return;
            }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(bdLocation.getDirection())
                    .latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude())
                    .build();
            mapUtil.baiduMap.setMyLocationData(locData);

            // p1=new LatLng(39.93923, 116.357428);
            LatLng p2 = new LatLng(bdLocation.getLatitude(),
                    bdLocation.getLongitude());
            mapUtil.animateMapStatus(p2, 17);

            if (isFirstLocation) {
                isFirstLocation = false;
                if (trackApp.getDepartmentLatLng() != null) {
                    distance = LocationUtil.getDistanceOfTwoPoints(trackApp.getDepartmentLatLng().latitude,
                            trackApp.getDepartmentLatLng().longitude, bdLocation.getLatitude(), bdLocation.getLongitude());
                    addr = bdLocation.getAddrStr();
                    List<Poi> pois = null;
                    if (bdLocation.getPoiList().size() > 0) {
                        pois = bdLocation.getPoiList();
                        addr += "(" + pois.get(0).getName() + ")";
                        p1 = p2;
                    }

                    address = "当前位置：" + addr;
                    distanceString = "距离单位：" + (int) distance + "米";
                } else {

                    address = "无法定位当前位置，请重新定位！";
                    distanceString = "无法计算与单位距离！";
                }

                setTextView();
            }
        }
    }
}
